package com.example.gpstest.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.gpstest.DataBean.GPSSharedPreference;
import com.example.gpstest.R;
import com.example.gpstest.Utils.GPSConst;
import com.example.gpstest.Utils.MD5;
import com.example.gpstest.Utils.SHA;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends AppCompatActivity {

    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.login)
    Button login;
    private static final String TAG = "LoginActivity";
    private final String str = Build.BRAND + "-" + Build.MODEL;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (hasRightAccount()) {
            startMainActivity();
        }
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        number.setText(MD5.md5(str).substring(11, 25));
        //password.setText("d648ad85477f7b");
        //password.setText(SHA.encrypt1(MD5.md5(str).substring(11, 25)).substring(11, 25));
    }
    private boolean hasRightAccount() {
        SharedPreferences sp = getSharedPreferences("account", MODE_PRIVATE);
        String password = sp.getString("password", "");
        if (password.equals(SHA.encrypt1(MD5.md5(str).substring(11, 25)).substring(11, 25))) {
            return true;
        }
        return false;
    }
    private void startMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }
    @OnClick(R.id.login)
    public void onViewClicked() {

        String input = password.getText().toString().trim();
        String str = number.getText().toString().trim();
        Log.i(TAG, "onClick>>>>>input:" + input + ", code:" + SHA.encrypt1(str).substring(11, 25));
        if (input.equals(SHA.encrypt1(str).substring(11, 25))) {
            startMainActivity();
            saveAccount(str, input);
        } else {
            Toast.makeText(this, "密码不正确!!", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveAccount(String number, String password) {
        SharedPreferences sp = getSharedPreferences("account", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("number", number);
        edit.putString("password", password);
        edit.apply();
    }
}
